package com.superafroman.utils.scanner.locater;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;

import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Implementation of {@link IClassLocater} that finds classes to scan inside a
 * web application.
 */
public class WebappClassLocater implements IClassLocater {

    private static final Log LOG = LogFactory.getLog(WebappClassLocater.class);

    private ServletContext servletContext;

    public WebappClassLocater(ServletContext servletContext) {
        this.servletContext = servletContext;
    }

    /**
     * @return
     *         A {@link List} containing {@link URI}s to /WEB-INF/classes and
     *         /WEB-INF/lib.
     */
    public List<URI> getClassLocations() {

        List<URI> locations = new ArrayList<URI>();

        try {
            locations.add(URI.create("file:///"
                    + URIUtil.encodeAll(servletContext
                            .getRealPath("/WEB-INF/classes"))));
        } catch (URIException e) {
            LOG.warn("Could not add /WEB-INF/classes to class locations.", e);
        }
        try {
            locations.add(URI.create("file:///"
                    + URIUtil.encodeAll(servletContext
                            .getRealPath("/WEB-INF/lib"))));
        } catch (URIException e) {
            LOG.warn("Could not add /WEB-INF/lib to class locations.", e);
        }

        return locations;
    }
}
